package com.sxy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sxy.controller.common.BaseContext;
import com.sxy.controller.common.R;
import com.sxy.pojo.AddressBook;
import com.sxy.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 宋鑫宇
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 保存用户地址信息
     *
     * @param addressBook
     * @return
     */
    @PostMapping
    public R<AddressBook> save(@RequestBody AddressBook addressBook) {
        //设置当前地址对应的用户id
        addressBook.setUserId(BaseContext.getCurrentId());

        //保存地址信息
        addressBookService.save(addressBook);

        return R.success(addressBook);
    }

    /**
     * 设置默认地址
     * @param addressBook
     * @return
     */
    @PutMapping("/default")
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook) {
        log.info("设置默认地址....");
        //新建条件对象
        LambdaUpdateWrapper<AddressBook> lqw = new LambdaUpdateWrapper<>();
        //添加条件,根据当前userid修改
        lqw.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        //设置 IsDefault 字段为0
        lqw.set(AddressBook::getIsDefault, 0);
        //将当前id的IsDefault字段全部设置为0
        addressBookService.update(lqw);

        //将  addressBook 对象的IsDefault属性设置为1
        addressBook.setIsDefault(1);

        //执行业务层方法
        addressBookService.updateById(addressBook);

        return R.success(addressBook);
    }

    /**
     * 查询指定用户的全部地址
     * @param addressBook
     * @return
     */
    @GetMapping("/list")
    public R<List<AddressBook>> list(AddressBook addressBook){
        addressBook.setUserId(BaseContext.getCurrentId());
        log.info("查询指定用户的全部地址");

        //创建条件查询对象
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        //添加条件，根据userid查询
        lqw.eq(addressBook.getUserId() != null,AddressBook::getUserId,BaseContext.getCurrentId());
        lqw.orderByDesc(AddressBook::getUpdateTime);

        //执行业务层方法并返回
        return R.success(addressBookService.list(lqw));
    }

    /**
     * 根据当前用户id查询默认地址
     * @return
     */
    @GetMapping("/default")
    public R<AddressBook> getByUserId(){
        //创建条件查询器
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,BaseContext.getCurrentId());

        AddressBook addressBook = addressBookService.getOne(lqw);

        return R.success(addressBook);
    }
}
